package com.zeros.mysplash.http.service;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.zeros.mysplash.bean.Common;
import com.zeros.mysplash.bean.Splash;
import com.zeros.mysplash.common.Constants;
import com.zeros.mysplash.http.network.HttpClient;
import com.zeros.mysplash.utils.DownLoadUtils;
import com.zeros.mysplash.utils.SerializableUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 启动页下载服务 on 2017/12/20.
 * 需要在清单里配置服务
 */

public class SplashDownLoadService extends IntentService{

    private static final int TYPE_ANDROID = 1;
    private static final String SPLASH_FILE_NAME = "splash.srr";
    private Splash mSplash;

    public SplashDownLoadService() {
        super("SplashDownLoad");
    }

    //开启服务
    public static void startDownLoadSplashImage(Context context, String action) {
        Intent intent = new Intent(context, SplashDownLoadService.class);
        intent.putExtra(Constants.EXTRA_DOWNLOAD, action);
        context.startService(intent);
    }


    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        if (intent != null) {
            String action = intent.getStringExtra(Constants.EXTRA_DOWNLOAD);
            if (action.equals(Constants.DOWNLOAD_SPLASH)) {
                loadSplashNetDate();    //网络处理
            }
        }
    }


    /**
     * 网络处理（工作线程）
     */
    private void loadSplashNetDate() {
        HttpClient.getInstance(this)                //相当于Retrofit
                .getSplashImage(TYPE_ANDROID)
//                .getSplashImage(Constants.API_DEBUG_SERVER_URL)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Common>() {
                               @Override
                               public void accept(Common common) throws Exception {
                                   if (common.isValid() && common.getAttachment() != null) {

                                       mSplash = common.getAttachment().getFlashScreen();
                                       //启动页
                                       String baiduImgurl = "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3189437162,1687026835&fm=27&gp=0.jpg";
//                                       String baiduImgurl = "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=823964781,330461961&fm=27&gp=0.jpg";
                                       //启动页跳转详情页
//                                       String baiduImgurl2 = "http://blog.csdn.net/zone_/article/details/66476733";
                                       String baiduImgurl2 = "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2249176906,2827736098&fm=27&gp=0.jpg";//图片
                                       String title = "启动页广告";
                                       if (mSplash == null) {
                                           mSplash = Splash.splash(title, baiduImgurl2, baiduImgurl, Constants.SPLASH_PATH);
                                       }
                                       Splash splashLocal = getSplashLocal();

                                       if (mSplash != null) {
                                           if (splashLocal == null) {
                                               Log.e("SplashDemo", "splashLocal 为空导致下载");
                                               startDownLoadSplash(Constants.SPLASH_PATH, mSplash.getBurl());


                                           } else if (isNeedDownLoad(splashLocal.getSavePath(), mSplash.getBurl())) {
                                               Log.e("SplashDemo", "isNeedDownLoad 导致下载");
                                               startDownLoadSplash(Constants.SPLASH_PATH, mSplash.getBurl());
                                           }

                                       } else {
                                           if (splashLocal != null) {
                                               File splashFile = SerializableUtils.getSerializableFile(Constants.SPLASH_PATH, Constants.SPLASH_FILE_NAME);
                                               if (splashFile.exists()) {
                                                   splashFile.delete();
                                                   Log.e("SplashDemo", "mScreen为空删除本地文件");
                                               }
                                           }
                                       }
                                   }
                               }
                           },
                        new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {

                            }
                        });
    }

    /**
     * 获取图片当地地址
     */
    private Splash getSplashLocal() {
        Splash splash = null;
        try {
            File splashFile = SerializableUtils.getSerializableFile(Constants.SPLASH_PATH, Constants.SPLASH_FILE_NAME);
            splash = (Splash) SerializableUtils.readObject(splashFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return splash;
    }


    /**
     * 是否需要下载
     * @param path 本地存储的图片绝对路径
     * @param url 网络获取url
     * @return 比较储存的 图片名称的哈希值与 网络获取的哈希值是否相同
     */
    private boolean isNeedDownLoad(String path, String url) {
        if (TextUtils.isEmpty(path)) {
            Log.e("SplashDemo","本地url " + TextUtils.isEmpty(path));
            Log.e("SplashDemo","本地url " + TextUtils.isEmpty(url));
            return true;
        }
        File file = new File(path);
        if (!file.exists()) {
            Log.e("SplashDemo","本地file " + file.exists());
            return true;
        }
        if (getImageName(path).hashCode() != getImageName(url).hashCode()) {
            Log.e("SplashDemo","path hashcode " + getImageName(path) + " " + getImageName(path).hashCode());
            Log.e("SplashDemo","url hashcode " + getImageName(url) + " " + getImageName(url).hashCode());
            return true;
        }
        return false;
    }


    /**
     * 获取图片名
     */
    private String getImageName(String url) {
        if (TextUtils.isEmpty(url)) {
            return "";
        }
        String[] split = url.split("/");
        String nameWith_ = split[split.length - 1];
        String[] split1 = nameWith_.split("\\.");
        return split1[0];
    }


    /**
     * 开始下载启动页
     * @param splashPath 存储地址
     * @param burl 网络url
     */
    private void startDownLoadSplash(String splashPath, String burl) {
        DownLoadUtils.downLoad(splashPath, new DownLoadUtils.DownLoadInterface() {
            @Override
            public void afterDownLoad(ArrayList<String> savePaths) {
                if (savePaths.size() == 1) {
                    Log.e("SplashDemo", "闪屏页面下载完成" + savePaths);
                    if (mSplash != null) {
                        mSplash.setSavePath(savePaths.get(0));
                    }
                    SerializableUtils.writeObject(mSplash, Constants.SPLASH_PATH + "/" + SPLASH_FILE_NAME);

                } else {
                    Log.e("SplashDemo", "闪屏页面下载失败" + savePaths);
                }
            }
        }, burl);
    }

}
